import ZWSJ from '@/assets/image/zwsj.png';
import { delete_writing, writing_sessions } from '@/services/ant-design-pro/docList';
import {
  AppstoreOutlined,
  BarsOutlined,
  DeleteOutlined,
  EllipsisOutlined,
  LoadingOutlined,
} from '@ant-design/icons';
import { Button, Dropdown, message, Modal, Pagination, Select, Tooltip } from 'antd';
import { nanoid } from 'nanoid';
import { stringify } from 'querystring';
import React, { useEffect, useRef, useState } from 'react';
import { history } from 'umi';
import './../index.less';
const dayjs = require('dayjs');
const DocLists: React.FC = (props: any) => {
  const [delId, setDelId] = useState<string>(''); //下拉列表
  const [openDelDialog, setOpenDelDialog] = useState<boolean>(false);
  const [reqLoad, setReqLoad] = useState<boolean>(false); //下拉列表
  const [selectList, setSelectList] = useState<any[]>([]); //下拉列表
  const [curSelect, setCurSelect] = useState<any>(null); //下拉选中
  const [listModal, setListModal] = useState<string>('card'); //模式 card or table
  const [tableList, setTableList] = useState<any[]>([]); //表格数据
  const [pageNum, setPageNum] = useState(1); // 页码
  const [total, setTotal] = useState(0); // 总数
  const [pageSize, setPageSize] = useState(10); // 总数
  const docCardTableBoxRef = useRef<any>(null);
  const [isEmpty, setIsEmpty] = useState(false);
  const { docTypeList, filterType } = props;
  const handleChange = (val: any) => {
    setPageNum(1);
    setCurSelect(val);
  };
  const showTag = (data: any) => {
    const writingTypeId = data.writing_type_id;
    let tagList: any = [];
    if (writingTypeId !== 10) {
      // 非自由写作
      let parallelism: any = {
        活动致辞: ['活动名称', '活动目的', '活动主题'],
        座谈会: ['会议名称', '发言人'],
      };
      //根据writingTypeId与docTypeList里的id对应 找出name
      let name = docTypeList.find((item: any) => item.id === writingTypeId)?.name;
      data.key_points.forEach((item: any) => {
        item.key = nanoid();
        if (parallelism[name]?.includes(item.title)) {
          tagList.push(item);
        }
        //parallelism[name]如果没有 则取key_points的前三个
        if (!parallelism[name]) {
          tagList = data.key_points.slice(0, 3);
        }
      });
    } else {
      // 自由写作
      const themeItem: any = {
        key: nanoid(),
        title: '文章主题',
        content: data.main_point?.title,
      };
      tagList.push(themeItem);
      const count = data.materials.length > 2 ? 2 : data.materials.length;
      for (let index = 0; index < count; index++) {
        const material = data.materials[index];
        const pointItem: any = {
          key: nanoid(),
          title: `文章观点${index + 1}`,
          content: material.main_body,
        };
        tagList.push(pointItem);
      }
    }
    return tagList;
  };
  //跳转到写作页面
  const goWritePage = (item: any) => {
    if (!item) return;
    const { id, writing_type_id } = item;
    const currentType = filterType(writing_type_id); //根据id匹配公文类型
    const query = {
      writing_type_id,
      writing_session_id: id, //writing_session_id 当前会话id
      type_name: currentType.typeTitle, //公文类型name
    };
    const queryStr = stringify(query);
    if (+writing_type_id !== 10) {
      history.push({
        pathname: `/conversation?${queryStr}`,
      });
    } else {
      history.push({
        pathname: `/highClassWrite?${queryStr}`,
      });
    }
  };
  //切换模式
  const toggleModal = () => {
    if (reqLoad) return;
    // card or table
    setListModal(listModal === 'card' ? 'table' : 'card');
  };
  useEffect(() => {
    if (docTypeList && docTypeList.length > 0) {
      let newList = docTypeList.map((item: any) => {
        return {
          id: item.id,
          key: nanoid(),
          value: item.id,
          label: item.display_name,
          disabled: !item.enabled,
        };
      });
      //添加全部
      newList.unshift({ value: '-1', label: '全部类型', key: nanoid(), id: '0' });
      setSelectList(newList);
      setCurSelect('-1');
    }
  }, [docTypeList]);

  const getList = async () => {
    setReqLoad(true);
    const params: any = {
      page: pageNum,
      per_page: pageSize,
    };
    if (curSelect !== '-1') {
      params.writing_type_id = curSelect;
    }
    const res = await writing_sessions(params);
    if (res.code === 0) {
      let list = res.data.writing_sessions || [];
      list = list.map((item: any) => {
        return {
          ...item,
          key: nanoid(),
          tagList: showTag(item),
        };
      });
      setTableList(list);
      setTotal(res.data.total_count);
      setReqLoad(false);
      if (res.data.total_count === 0) {
        setIsEmpty(true);
      } else {
        setIsEmpty(false);
      }
    } else {
      setReqLoad(false);
      message.open({
        type: 'error',
        content: res.msg,
      });
    }
  };
  // useEffect(() => {
  //   getList();
  // }, []);
  const formatAtTime = (timestamp: any) => {
    return dayjs(timestamp).format('YYYY.MM.DD HH:mm:ss');
  };
  const changePag = (page: any, pageSize: any) => {
    setPageNum(page);
    setPageSize(pageSize);
  };
  useEffect(() => {
    if (pageNum && pageSize && curSelect && docTypeList && docTypeList.length > 0) {
      getList();
    }
  }, [pageNum, pageSize, curSelect, docTypeList]);
  const hideDelModal = () => {
    setOpenDelDialog(false);
  };
  //删除 下拉点击事件
  const dropDownClick: (v: any, item: any) => void = (v, item) => {
    v.domEvent.stopPropagation();
    setDelId(item.id);
    if (v.key === '2') {
      setOpenDelDialog(true);
    }
  };
  ///删除询问框 - 确定
  const onConfirmDel = async () => {
    const res = await delete_writing(delId);
    if (res.code === 0) {
      const data = tableList.filter((item) => item.id !== delId);
      getList();
      message.open({
        type: 'success',
        content: '删除成功',
      });
      if (data.length < 1) {
        setIsEmpty(true);
      }
      hideDelModal();
    }
  };

  const items = [
    {
      label: (
        <div>
          <DeleteOutlined />
          <span style={{ marginLeft: '5px' }}>删除文档</span>
        </div>
      ),
      key: '2',
    },
  ];
  return (
    <>
      <div className="headerBox" style={{ marginTop: '20px' }}>
        <span className="header-hd">我的文档</span>
        <div className="header-bd">
          <Select
            value={curSelect}
            style={{ width: 150, height: 39 }}
            onChange={handleChange}
            options={selectList}
            disabled={reqLoad}
          />
          <span className="toggleType" onClick={toggleModal}>
            <Tooltip placement="top" title="切换" color="blue">
              {!reqLoad ? (
                listModal === 'card' ? (
                  <AppstoreOutlined />
                ) : (
                  <BarsOutlined />
                )
              ) : (
                <LoadingOutlined></LoadingOutlined>
              )}
            </Tooltip>
          </span>
        </div>
      </div>
      <div className={`docCardTableWrap ${listModal === 'table' ? 'wrapAutoHeight' : ''}`}>
        <div className="noDataBox" style={{ display: isEmpty ? 'flex' : 'none' }}>
          <img src={ZWSJ} height={30} width={30} />
          <div className="noDataTip">
            您当前没有该类型的文档。请按上方提示选择文章类型，我将为您立即创建。
          </div>
          <div className="noDataInfo">
            领导您好，我是小麦，专为您快速撰写文章的AI共享实习生。告诉我您的想法，
          </div>
          <div className="noDataInfo">我将为您自动生成完整文档，助您提高工作效率。</div>
        </div>
        <div
          style={{ display: !isEmpty ? 'block' : 'none' }}
          ref={docCardTableBoxRef}
          className={`docCardTableBox ${listModal === 'card' ? 'cardModal' : 'tableModal'}`}
        >
          {tableList &&
            tableList.length > 0 &&
            tableList.map((item) => {
              let writingType = filterType(item.writing_type_id);
              // console.log(writingType);
              return (
                <div className="docCard" key={item.id}>
                  <div className="docCardList" onClick={() => goWritePage(item)}>
                    <div className="cardHeadBox">
                      <span className="cardHead-hd" style={{ background: `${writingType.color}` }}>
                        {writingType.typeTitle}
                      </span>
                      <span className="cardHead-bd">{formatAtTime(item.updated_at)}</span>
                    </div>
                    {item.tagList &&
                      item.tagList.length > 0 &&
                      item.tagList.map((itemTag: any) => {
                        return (
                          <div key={itemTag.key} className="cardContBox">
                            <span className="cardCont-hd">{itemTag.title}：</span>
                            <span className="cardCont-bd">{itemTag.content || '空'}</span>
                          </div>
                        );
                      })}
                    {/* {+item.writing_type_id === 10 && (
                      <div className="cardContBox" style={{ height: 'auto' }}>
                        <span className="cardCont-theme">{item.last_document.title}</span>
                      </div>
                    )} */}
                    <div className="delIocnBox">
                      <Dropdown
                        menu={{ items, onClick: (v) => dropDownClick(v, item) }}
                        className="card-more"
                      >
                        <div
                          style={{ cursor: 'pointer', width: '20px', textAlign: 'right' }}
                          onClick={(e) => e.stopPropagation()}
                        >
                          <EllipsisOutlined />
                        </div>
                      </Dropdown>
                    </div>
                  </div>
                  <div className="docTableList" onClick={() => goWritePage(item)}>
                    <span className="docTable-hd" style={{ background: `${writingType.color}` }}>
                      {writingType.typeTitle}
                    </span>
                    <span className="docTable-bd">
                      {item.tagList &&
                        item.tagList.length > 0 &&
                        item.tagList.map((itemTag: any) => {
                          return (
                            <span key={itemTag.key}>
                              {itemTag.title}：{itemTag.content || '空'}；{' '}
                            </span>
                          );
                        })}
                      {+item.writing_type_id === 10 && <span>{item.last_document.title}</span>}
                      {/* 活动地点：深圳；活动名称：推动绿色低碳循环发展大会；活动目的：旨在推动实现区域更高质量、更加公平… */}
                    </span>
                    <span className="docTable-ft">{formatAtTime(item.updated_at)}</span>
                    <div className="docTable-del">
                      <Dropdown
                        menu={{ items, onClick: (v) => dropDownClick(v, item) }}
                        className="card-more"
                      >
                        <div
                          style={{ cursor: 'pointer', width: '20px', textAlign: 'right' }}
                          onClick={(e) => e.stopPropagation()}
                        >
                          <EllipsisOutlined />
                        </div>
                      </Dropdown>
                    </div>
                  </div>
                </div>
              );
            })}
        </div>
        <div className="docCardTablePagination" style={{ display: !isEmpty ? 'block' : 'none' }}>
          <Pagination
            defaultPageSize={pageSize}
            onChange={changePag}
            current={pageNum}
            total={total}
            disabled={reqLoad}
            showSizeChanger={false}
          />
        </div>
        <Modal
          title="确认删除"
          open={openDelDialog}
          onOk={onConfirmDel}
          onCancel={hideDelModal}
          width={350}
          okText="确认"
          cancelText="取消"
          footer={[
            <Button key="back" onClick={hideDelModal}>
              取消
            </Button>,
            <Button type="primary" danger onClick={onConfirmDel} key="confirm">
              确认
            </Button>,
          ]}
        >
          <p>确定删除该文档吗?</p>
        </Modal>
      </div>
    </>
  );
};

export default DocLists;
